package com.swjd.huffmantree;

import java.util.*;

/**
 * 哈夫曼编码压缩
 */
public class HuffmanCode {
    public static void main(String[] args) {
        //需要编码的字符串
        String str = "i like like like java do you like a java";
        byte[] zip = huffmanZip(str);
        System.out.println("二进制压缩赫夫曼编码值："+Arrays.toString(zip));
/*        //将字符串转成字节数组
        byte[] bytes = str.getBytes();
        System.out.println(bytes.length);
        //将字节数组转成哈夫曼节点集合
        ArrayList<HuffManNode> nodes = getNodes(bytes);
//        System.out.println(nodes);
//        System.out.println(createHuffmanTree(nodes));
        //将哈夫曼节点集合转成哈夫曼树
        preOrder(createHuffmanTree(nodes));
        //测试哈夫曼编码表
        StringBuilder stringBuilder = new StringBuilder();
        getCodes(createHuffmanTree(nodes), "", stringBuilder);
        System.out.println("哈夫曼编码表：" + huffmanCodes);
        byte[] zip = zip(bytes, huffmanCodes);
        System.out.println("二进制压缩赫夫曼编码值："+Arrays.toString(zip));*/
    }

    /**
     * 赫夫曼编码封装
     * @param str 需要编码的字符串
     * @return 编码结果
     */
    private static byte[] huffmanZip(String str){
        //将字符串转成字节数组
        byte[] bytes = str.getBytes();
        System.out.println(bytes.length);
        //将字节数组转成哈夫曼节点集合
        ArrayList<HuffManNode> nodes = getNodes(bytes);
        //将哈夫曼节点集合转成哈夫曼树
        preOrder(createHuffmanTree(nodes));
        //测试哈夫曼编码表
        StringBuilder stringBuilder = new StringBuilder();
        getCodes(createHuffmanTree(nodes), "", stringBuilder);
        System.out.println("哈夫曼编码表：" + huffmanCodes);
        byte[] zip = zip(bytes, huffmanCodes);
        System.out.println("二进制压缩赫夫曼编码值："+Arrays.toString(zip));
        return zip;
    }

    /**
     * 构建哈夫曼节点
     *
     * @param bytes 字节数组
     * @return 哈夫曼节点集合
     */
    private static ArrayList<HuffManNode> getNodes(byte[] bytes) {
        ArrayList<HuffManNode> huffManNodes = new ArrayList<>();
        //存储每个byte出现的次数
        HashMap<Byte, Integer> counts = new HashMap<>();
        for (byte b : bytes) {
            Integer count = counts.get(b);//获取当前这个字节
            if (count == null) {//为空代表还没有读取过
                counts.put(b, 1);
            } else {
                counts.put(b, count + 1);//不为空代表已经读取过了，这次再次存储，就加一
            }
        }
        //遍历map
        for (Map.Entry<Byte, Integer> entry : counts.entrySet()) {
            //将map中的key即字节和value即权重 放到哈夫曼树中 再放入集合
            huffManNodes.add(new HuffManNode(entry.getKey(), entry.getValue()));
        }
        return huffManNodes;
    }

    /**
     * 构建赫夫曼树
     *
     * @param huffManNodes 赫夫曼树节点集合
     * @return 构建完成的根节点
     */
    public static HuffManNode createHuffmanTree(ArrayList<HuffManNode> huffManNodes) {
        while (huffManNodes.size() > 1) {
            Collections.sort(huffManNodes);
            System.out.println(huffManNodes);
            HuffManNode leftNode = huffManNodes.get(0);
            HuffManNode rightNode = huffManNodes.get(1);
            HuffManNode huffManNode = new HuffManNode(null, leftNode.weight + rightNode.weight);
            huffManNode.right = rightNode;
            huffManNode.left = leftNode;
            huffManNodes.add(huffManNode);
            huffManNodes.remove(leftNode);
            huffManNodes.remove(rightNode);
        }
        return huffManNodes.get(0);
    }

    private static void preOrder(HuffManNode root) {
        if (root != null) {
            root.preOrder();
        } else {
            System.out.println("树空!");
        }
    }

    /**
     * 将传入的叶子节点进行赫夫曼编码
     *
     * @param node 叶子节点
     * @param code 赫夫曼路径 左子节点：0 右子节点：1
     * @param stringBuilder 拼接后的赫夫曼编码
     */
    //编码表
    static Map<Byte, String> huffmanCodes = new HashMap<Byte, String>();

    private static void getCodes(HuffManNode node, String code, StringBuilder stringBuilder) {
        StringBuilder stringBuilder2 = new StringBuilder(stringBuilder);
        //进行赫夫曼路径拼接成编码
        stringBuilder2.append(code);
        if (node != null) {
            //判断当前node是叶子节点还是非叶子节点
            if (node.data == null) {
                //非叶子节点
                //向左递归
                getCodes(node.left, "0", stringBuilder2);
                //向右递归
                getCodes(node.right, "1", stringBuilder2);
            } else {
                //将节点和其对应的编码加入编码表中
                huffmanCodes.put(node.data, stringBuilder2.toString());
            }
        }
    }

    /**
     * 将字节数组配合赫夫曼编码表转换为赫夫曼编码数组
     *
     * @param bytes        字节数组
     * @param huffmanCodes 赫夫曼编码表
     * @return 赫夫曼编码后的数组
     */
    private static byte[] zip(byte[] bytes, Map<Byte, String> huffmanCodes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (byte b : bytes) {
            //从编码表中获得相应元素的编码，再加入到stringBuilder中
            stringBuilder.append(huffmanCodes.get(b));
        }
        System.out.println("赫夫曼编码值："+stringBuilder);
        //获得要创建的数组长度
        int len;
        if (stringBuilder.length() % 8 == 0) {
            len = stringBuilder.length() / 8;
        } else {
            len = stringBuilder.length() / 8 + 1;
        }
        //创建存储编码的byte数组
        byte[] by = new byte[len];
        int index = 0;//记录数组下标
        for (int i = 0; i < stringBuilder.length(); i = i + 8) {
            //因为是每八位对应一个字节，所以步进是8位
            String strByte;
            if (i + 8 > stringBuilder.length()) {
                //不够8位
                strByte = stringBuilder.substring(i);
            } else {
                strByte = stringBuilder.substring(i, i + 8);
            }
            //将strByte转成byte，以二进制存储放入哈夫曼字节数组
            by[index] = (byte) Integer.parseInt(strByte, 2);
            index++;
        }
        return by;
    }
}

/**
 * 赫夫曼节点
 * 实现Comparable接口用来排序
 */
class HuffManNode implements Comparable<HuffManNode> {
    Byte data;//存放数据
    int weight;//权重(字符出现的次数)
    HuffManNode left;
    HuffManNode right;

    public HuffManNode(Byte data, int weight) {
        this.data = data;
        this.weight = weight;
    }


    @Override
    public int compareTo(HuffManNode o) {
        //升序排序 从小到大
        return this.weight - o.weight;
    }

    @Override
    public String toString() {
        return "HuffManNode{" +
                "data=" + data +
                ", weight=" + weight +
                '}';
    }

    //前序遍历
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if ((this.right != null)) {
            this.right.preOrder();
        }
    }
}